<template>
  <div>
    <el-card class="box-card">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="级别">
          <el-select v-model="queryForm.level" placeholder="请选择级别" clearable class="select-input">
            <el-option label="INFO" value="INFO"></el-option>
            <el-option label="WARN" value="WARN"></el-option>
            <el-option label="ERROR" value="ERROR"></el-option>
            <el-option label="DEBUG" value="DEBUG"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请求方法">
          <el-select v-model="queryForm.method" placeholder="请选择请求方法" clearable class="select-input">
            <el-option label="GET" value="GET"></el-option>
            <el-option label="POST" value="POST"></el-option>
            <el-option label="PUT" value="PUT"></el-option>
            <el-option label="DELETE" value="DELETE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="action-bar">
        <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="logList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        highlight-current-row
        stripe
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="level" label="级别">
          <template #default="scope">
            <el-tag 
              :type="scope.row.level === 'ERROR' ? 'danger' : scope.row.level === 'WARN' ? 'warning' : scope.row.level === 'DEBUG' ? 'info' : 'success'"
              effect="dark"
            >{{ scope.row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="日志内容" show-overflow-tooltip></el-table-column>
        <el-table-column prop="url" label="URL地址" show-overflow-tooltip></el-table-column>
        <el-table-column prop="method" label="请求方法">
          <template #default="scope">
            <el-tag 
              :type="scope.row.method === 'GET' ? 'success' : scope.row.method === 'POST' ? 'warning' : scope.row.method === 'DELETE' ? 'danger' : 'info'"
              effect="plain"
              size="small"
            >{{ scope.row.method }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" ></el-table-column>
        <el-table-column prop="createdTime" label="创建时间">
          <template #default="scope">
            {{ scope.row.createdTime}}
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleView(scope.row)">
              <el-icon><View /></el-icon> 查看
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryForm.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        ></el-pagination>
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog title="系统日志详情" v-model="dialogVisible" width="65%" destroy-on-close>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="ID">
          <el-tag type="info">{{ selectedLog.id }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="级别">
          <el-tag 
            :type="selectedLog.level === 'ERROR' ? 'danger' : selectedLog.level === 'WARN' ? 'warning' : selectedLog.level === 'DEBUG' ? 'info' : 'success'"
            effect="dark"
          >{{ selectedLog.level }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="日志内容">{{ selectedLog.message }}</el-descriptions-item>
        <el-descriptions-item label="URL地址">
          <el-link type="primary" :underline="false">{{ selectedLog.url }}</el-link>
        </el-descriptions-item>
        <el-descriptions-item label="请求方法">
          <el-tag 
            :type="selectedLog.method === 'GET' ? 'success' : selectedLog.method === 'POST' ? 'warning' : selectedLog.method === 'DELETE' ? 'danger' : 'info'"
            effect="plain"
          >{{ selectedLog.method }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ selectedLog.ip }}</el-descriptions-item>
        <el-descriptions-item label="异常信息" v-if="selectedLog.exception">
          <el-alert
            type="error"
            :closable="false"
            show-icon
          >
            <pre class="error-message">{{ selectedLog.exception }}</pre>
          </el-alert>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ selectedLog.createdTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getSysLogPageList, getSysLogById, deleteSysLogById, deleteSysLogBatch } from '@/api/sysLog'
import { Search, Refresh, Delete, View } from '@element-plus/icons-vue'

// 查询表单
const queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  level: '',
  method: '',
  startTime: '',
  endTime: ''
})

// 日期范围选择
const dateRange = ref([])
const handleDateChange = (val) => {
  if (val) {
    queryForm.startTime = val[0]
    queryForm.endTime = val[1]
  } else {
    queryForm.startTime = ''
    queryForm.endTime = ''
  }
}

// 状态数据
const loading = ref(false)
const logList = ref([])
const total = ref(0)
const selectedIds = ref([])
const dialogVisible = ref(false)
const selectedLog = ref({})

// 获取日志列表
const getList = async () => {
  loading.value = true
  try {
    // 创建一个新对象来保存要发送的参数
    const params = { ...queryForm }
    
    // 如果开始时间或结束时间为空，则从参数中删除
    if (!params.startTime) {
      delete params.startTime
    }
    if (!params.endTime) {
      delete params.endTime
    }
    
    const response = await getSysLogPageList(params)
    logList.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    console.error('获取系统日志列表失败', error)
    ElMessage.error('获取系统日志列表失败')
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryForm.pageNum = 1
  getList()
}

// 重置查询条件
const resetQuery = () => {
  queryForm.pageNum = 1
  queryForm.level = ''
  queryForm.method = ''
  queryForm.startTime = ''
  queryForm.endTime = ''
  dateRange.value = []
  getList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页相关方法
const handleSizeChange = (size) => {
  queryForm.pageSize = size
  getList()
}

const handleCurrentChange = (current) => {
  queryForm.pageNum = current
  getList()
}

// 查看详情
const handleView = async (row) => {
  try {
    const response = await getSysLogById(row.id)
    selectedLog.value = response.data
    dialogVisible.value = true
  } catch (error) {
    console.error('获取系统日志详情失败', error)
    ElMessage.error('获取系统日志详情失败')
  }
}

// 删除单条记录
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该系统日志记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSysLogById(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条系统日志记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSysLogBatch(selectedIds.value)
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
    }
  }).catch(() => {})
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.error-message {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #fef0f0;
  padding: 10px;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  font-family: monospace;
  margin: 0;
}

.select-input {
  width: 220px;
}
</style> 